# quotes.py
# Author: Peter Sovietov

import random

q_file = 'quotes.txt'

q = []

find_pat = ''
find_result = []

q_empty = 'quotes.txt is empty'
not_found = 'quote not found'

def q_load():
    global q
    q = []
    f = open(q_file, 'r')
    for line in f:
        line = line.split(' ', 1)
        q += [[int(line[0]), line[1].rstrip()]]
    f.close()

def q_save():
    f = open(q_file, 'w+')
    for l in q:
        f.write(str(l[0]) + ' ' + l[1] + '\n')       
    f.close()

def q_random():
    if not len(q):
        return q_empty
    r = random.choice(q)
    return '#' + str(r[0]) + ' ' + r[1]

def q_add(text):
    global q
    if not len(q):
        n = 0
    else:
        n = q[-1][0] + 1
    q += [[n, text]]
    q_save()
    return 'quote #' + str(n) + ' added'

def q_remove(n):
    global q
    if not len(q):
        return q_empty
    for i in range(0, len(q)):
        if q[i][0] == n:
            del q[i]
            q_save()
            return 'quote #' + str(n) + ' removed'
    return not_found

def q_find(pat):
    global find_pat, find_result
    if pat != find_pat:
        find_pat = pat
        find_result = []
        for l in q:
            l = '#' + str(l[0]) + ' ' + l[1]
            if l.find(pat) != -1:
                find_result += [l]
    if not len(find_result):
        return not_found
    return find_result.pop(0)
